package com.warom.sdg.repository;

import android.content.Context;
import android.util.Log;

import com.warom.sdg.dao.UserDao;
import com.warom.sdg.database.SdgDatabase;
import com.warom.sdg.model.UserEntity;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/**
 * 用户仓库类
 * 提供用户数据库操作的高级接口，管理UserDao实例
 */
public class UserRepository {
    private static final String TAG = "UserRepository";
    
    // 数据库和DAO
    private final SdgDatabase database;
    private final UserDao userDao;
    
    // 线程池执行器，用于异步操作
    private final ExecutorService executor;
    
    /**
     * 构造函数
     * @param context 上下文
     */
    public UserRepository(Context context) {
        database = SdgDatabase.getInstance(context);
        userDao = database.getUserDao();
        executor = Executors.newFixedThreadPool(2); // 创建线程池
    }
    
    /**
     * 插入用户记录
     * @param user 用户实体
     * @param successCallback 成功回调，返回新插入的ID
     * @param errorCallback 错误回调，返回错误信息
     */
    public void insert(final UserEntity user, Consumer<Long> successCallback, Consumer<String> errorCallback) {
        Log.d(TAG, "插入用户: " + user.toString());
        executor.execute(() -> {
            try {
                long id = userDao.insert(user);
                Log.d(TAG, "用户插入成功，ID: " + id);
                if (successCallback != null) {
                    successCallback.accept(id);
                }
            } catch (Exception e) {
                String errorMsg = "用户插入失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 更新用户信息
     * @param user 用户实体
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void update(final UserEntity user, Runnable onComplete, Consumer<String> onError) {
        Log.d(TAG, "更新用户: " + user.toString());
        executor.execute(() -> {
            try {
                userDao.update(user);
                Log.d(TAG, "用户更新成功，ID: " + user.getId());
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "用户更新失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 删除用户
     * @param user 用户实体
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void delete(final UserEntity user, Runnable onComplete, Consumer<String> onError) {
        Log.d(TAG, "删除用户: " + user.toString());
        executor.execute(() -> {
            try {
                userDao.delete(user);
                Log.d(TAG, "用户删除成功，ID: " + user.getId());
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "用户删除失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 获取所有用户
     * @param successCallback 成功回调，返回用户列表
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getAllUsers(Consumer<List<UserEntity>> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                List<UserEntity> userList = userDao.getAllUsers();
                if (successCallback != null) {
                    successCallback.accept(userList);
                }
            } catch (Exception e) {
                String errorMsg = "获取所有用户失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据ID获取用户
     * @param userId 用户ID
     * @param successCallback 成功回调，返回用户实体
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getUserById(final long userId, Consumer<UserEntity> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                UserEntity user = userDao.getUserById(userId);
                if (user != null) {
                    if (successCallback != null) {
                        successCallback.accept(user);
                    }
                } else {
                    String errorMsg = "未找到ID为 " + userId + " 的用户";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "获取用户失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据用户名获取用户
     * @param username 用户名
     * @param successCallback 成功回调，返回用户实体
     * @param errorCallback 错误回调，返回错误信息
     */
    public void getUserByUsername(final String username, Consumer<UserEntity> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                UserEntity user = userDao.getUserByUsername(username);
                if (user != null) {
                    if (successCallback != null) {
                        successCallback.accept(user);
                    }
                } else {
                    String errorMsg = "未找到用户名为 " + username + " 的用户";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "获取用户失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 验证用户登录
     * @param username 用户名
     * @param password 密码
     * @param successCallback 成功回调，返回用户实体
     * @param errorCallback 错误回调，返回错误信息
     */
    public void verifyLogin(final String username, final String password, Consumer<UserEntity> successCallback, Consumer<String> errorCallback) {
        executor.execute(() -> {
            try {
                UserEntity user = userDao.verifyLogin(username, password);
                if (user != null) {
                    if (successCallback != null) {
                        successCallback.accept(user);
                    }
                } else {
                    String errorMsg = "用户名或密码错误";
                    Log.e(TAG, errorMsg);
                    if (errorCallback != null) {
                        errorCallback.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "验证登录失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (errorCallback != null) {
                    errorCallback.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 更新用户最后登录时间
     * @param userId 用户ID
     * @param lastLoginTime 最后登录时间
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void updateLastLoginTime(final long userId, final long lastLoginTime, Runnable onComplete, Consumer<String> onError) {
        executor.execute(() -> {
            try {
                userDao.updateLastLoginTime(userId, lastLoginTime);
                Log.d(TAG, "更新用户最后登录时间成功，ID: " + userId);
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "更新用户最后登录时间失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 删除所有用户
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void deleteAllUsers(Runnable onComplete, Consumer<String> onError) {
        executor.execute(() -> {
            try {
                userDao.deleteAll();
                Log.d(TAG, "已删除所有用户");
                if (onComplete != null) {
                    onComplete.run();
                }
            } catch (Exception e) {
                String errorMsg = "删除所有用户失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
    
    /**
     * 根据ID删除用户
     * @param userId 用户ID
     * @param onComplete 操作完成回调
     * @param onError 错误回调
     */
    public void deleteById(final long userId, Runnable onComplete, Consumer<String> onError) {
        executor.execute(() -> {
            try {
                // 先获取用户
                UserEntity user = userDao.getUserById(userId);
                if (user != null) {
                    userDao.delete(user);
                    Log.d(TAG, "用户删除成功，ID: " + userId);
                    if (onComplete != null) {
                        onComplete.run();
                    }
                } else {
                    String errorMsg = "删除失败: 未找到ID为 " + userId + " 的用户";
                    Log.e(TAG, errorMsg);
                    if (onError != null) {
                        onError.accept(errorMsg);
                    }
                }
            } catch (Exception e) {
                String errorMsg = "根据ID删除用户失败: " + e.getMessage();
                Log.e(TAG, errorMsg, e);
                if (onError != null) {
                    onError.accept(errorMsg);
                }
            }
        });
    }
} 